package pers.xx.sbm.service.serviceImpl;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.xx.sbm.dao.ReportDataCountyMapper;
import pers.xx.sbm.dao.ReportDataMapper;
import pers.xx.sbm.service.ReportDataCountyService;
import pers.xx.sbm.vo.ProjectIndicatorsVo;
import pers.xx.sbm.vo.RoleSampleVo;
import pers.xx.sbm.vo.TotalSampleVo;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportDataCountyServiceImpl implements ReportDataCountyService {

    @Autowired
    private ReportDataCountyMapper reportDataCountyMapper;

    @Autowired
    private ReportDataMapper reportDataMapper;

    private static int CURRENT_YEAR = LocalDate.now().getYear() - 1;

    private double areaRate = 0.0;
    private double cityRate =0.0;


    @Override
    public List<RoleSampleVo> getRoleSampleCount(String sysCode) {
        List<RoleSampleVo> roleSampleVos = null;
        if("5201".equals(sysCode)){
            roleSampleVos = reportDataCountyMapper.getCityCenterSampleCount(sysCode);
        }else{
            roleSampleVos = reportDataCountyMapper.getRoleSampleCount(sysCode);
        }
        int studentSum = 0, teacherSum = 0, parentSum = 0, yzSum = 0, rddbSum = 0;

        //第一遍 循环计算角色的总数量，各学段的总数量
        for (RoleSampleVo roleSampleVo : roleSampleVos) {
            roleSampleVo.setData();
            if (roleSampleVo.getStudentNum() != null) {
                studentSum += roleSampleVo.getStudentNum();
            }
            if (roleSampleVo.getTeacherNum() != null) {
                teacherSum += roleSampleVo.getTeacherNum();
            }
            if (roleSampleVo.getParentNum() != null) {
                parentSum += roleSampleVo.getParentNum();
            }
            if (roleSampleVo.getYzNum() != null) {
                yzSum += roleSampleVo.getYzNum();
            }
            if (roleSampleVo.getRddbNum() != null) {
                rddbSum += roleSampleVo.getRddbNum();
            }
        }
        //第二遍 计算百分比

        for (RoleSampleVo roleSampleVo : roleSampleVos) {
            if (studentSum != 0) {
                if (roleSampleVo.getStudentNum() != null)
                    roleSampleVo.setStudentPercent(count(roleSampleVo.getStudentNum(), studentSum));
            }

            if (teacherSum != 0) {
                if (roleSampleVo.getTeacherNum() != null)
                    roleSampleVo.setTeacherPercent(count(roleSampleVo.getTeacherNum(), teacherSum));
            }
            if (parentSum != 0) {
                if (roleSampleVo.getParentNum() != null)
                    roleSampleVo.setParentPercent(count(roleSampleVo.getParentNum(), parentSum));
            }

            if (yzSum != 0) {
                if (roleSampleVo.getYzNum() != null)
                    roleSampleVo.setYzPercent(count(roleSampleVo.getYzNum(), yzSum));
            }
            if (rddbSum != 0) {
                if (roleSampleVo.getRddbNum() != null)
                    roleSampleVo.setRddbPercent(count(roleSampleVo.getRddbNum(), rddbSum));
            }
        }
        RoleSampleVo roleSampleVo = new RoleSampleVo();//构造汇总数据
        roleSampleVo.setStudentNum(studentSum);
        roleSampleVo.setStudentPercent(100.0);
        roleSampleVo.setTeacherNum(teacherSum);
        roleSampleVo.setTeacherPercent(100.0);
        roleSampleVo.setParentNum(parentSum);
        roleSampleVo.setParentPercent(100.0);
        roleSampleVo.setYzNum(yzSum);
        roleSampleVo.setYzPercent(100.0);
        roleSampleVo.setRddbNum(rddbSum);
        roleSampleVo.setRddbPercent(100.0);
        roleSampleVo.setAllNum(studentSum + teacherSum + parentSum + yzSum + rddbSum);
        roleSampleVo.setXd("合计");
        roleSampleVos.add(roleSampleVo);
        return roleSampleVos;
    }


    /**
     * @description 小数点处理
     * @author XieXing
     * @date 2021/12/16 15:22
     */
    private double count(int part, int all) {
        Double f = part * 1.0 / all * 100;
        BigDecimal bg = new BigDecimal(f);
        return bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    @Override
    public String queryTotalSatisfactionByArea(String areaName) {
        //区县总体满意率（无%）
        areaRate =  reportDataCountyMapper.queryTotalSatisfactionRate(areaName,"","");
        //市总体满意率
        if(cityRate == 0) {
            List<TotalSampleVo> result = reportDataMapper.queryAreaSatisfactionByXdAndRole("","");
            String satisfiedRate = getSatisfiedRate(result);
            cityRate = Double.parseDouble(satisfiedRate.substring(0,satisfiedRate.length() - 1));
        }
        if(areaName.equals("市属") || areaName.equals("贵安新区")) {
            return "此次调查采集的数据分析显示，"+areaName+"综合满意率为" + areaRate +"%。"+ compareCity(areaRate,cityRate);
        }else {
            double lastRate = reportDataCountyMapper.queryHistoryData(areaName,"-1","-1",String.valueOf(CURRENT_YEAR - 1)).get(0);
            return "此次调查采集的数据分析显示，全区综合满意率为" + areaRate +"%," + compareLastYear(areaRate,lastRate) + "。" + compareCity(areaRate,cityRate);
        }
    }

    @Override
    public Map<String, List<Double>> areaHistoryList(String areaName) {
        Map<String, List<Double>> dataMap = new HashMap();

        List<TotalSampleVo> result = reportDataMapper.queryAreaSatisfactionByXdAndRole("", "");
        String satisfiedRate = getSatisfiedRate(result);
        double cityRoleRate = Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1));
        if(areaName.equals("市属") || areaName.equals("贵安新区") ) {
            Double areaCurrentYear =  reportDataCountyMapper.queryTotalSatisfactionRate(areaName,"","");
            List<Double> area = new ArrayList<>();
            area.add(areaCurrentYear);
            area.add(cityRoleRate);
            dataMap.put(String.valueOf(CURRENT_YEAR), area);
        }else {
            List<Double> areaHistoryList = reportDataCountyMapper.queryHistoryData(areaName,"-1","-1","");
            List<Double> cityHistoryList = reportDataCountyMapper.queryHistoryData("均值","-1","-1","");
            areaHistoryList.add(areaRate);
            cityHistoryList.add(cityRate);
            dataMap.put(areaName, areaHistoryList);
            dataMap.put("贵阳市", cityHistoryList);
        }
        return dataMap;
    }

    @Override
    public String queryXdTotalSatisfactionByArea(String areaName) {
        List<TotalSampleVo> result = reportDataCountyMapper.queryXdSatisfactionByArea(areaName);
        if (areaName.equals("市属") || areaName.equals("贵安新区") ) {
            return CURRENT_YEAR + "年"+areaName+"四个学段综合满意率从高到低分别为：" + getXdRateString(result);
        } else {
            //今年均值
            String satisfiedRate = getSatisfiedRate(result);
            double currentYearAverage = Double.parseDouble(satisfiedRate.substring(0,satisfiedRate.length() - 1));
            //查询上年数据
            List<TotalSampleVo> lastYearData = reportDataCountyMapper.queryXdHistoryData(areaName,"-1",String.valueOf(CURRENT_YEAR - 1));
            double lastYearAverage = reportDataCountyMapper.queryHistoryData(areaName, "-1", "-1", String.valueOf(CURRENT_YEAR - 1)).get(0);
            return CURRENT_YEAR + "年"+areaName+"四个学段综合满意率从高到低分别为：" + getXdRateString(result) + xdCurrentYearcompareLastYear(currentYearAverage,lastYearAverage,result,lastYearData);
        }
    }


    @Override
    public Map<String, List<Double>>  queryXdTotalSatisfactionRateByArea(String areaName) {
        Map<String, List<Double>> dataMap = new HashMap();
        List<Double> arrayYearBeforeLast = reportDataCountyMapper.queryHistoryData(areaName,"","-1",String.valueOf(CURRENT_YEAR - 2));
        List<Double> arrayLastYear = reportDataCountyMapper.queryHistoryData(areaName,"","-1",String.valueOf(CURRENT_YEAR - 1));
        ArrayList<Double> arrayCurrentYear = new ArrayList<Double>();

        List<TotalSampleVo> AreaSatisfactionByRole = reportDataCountyMapper.queryXdSatisfactionByArea(areaName);
        String satisfiedRate = getSatisfiedRate(AreaSatisfactionByRole);
        arrayCurrentYear.add(Double.parseDouble(satisfiedRate.substring(0,satisfiedRate.length() - 1)));

        for (TotalSampleVo data : AreaSatisfactionByRole) {
            arrayCurrentYear.add(getPercentNo(Double.parseDouble(data.getValue().toString()),5));
        }


        dataMap.put(String.valueOf(CURRENT_YEAR - 2), arrayYearBeforeLast);
        dataMap.put(String.valueOf(CURRENT_YEAR - 1), arrayLastYear);
        dataMap.put(String.valueOf(CURRENT_YEAR), arrayCurrentYear);
        return dataMap;
    }

    @Override
    public String queryRoleTotalSatisfactionByAreaAndRole(String areaName,String role) {
        //区县总体满意率（无%）
        Double areaRoleRate =  reportDataCountyMapper.queryTotalSatisfactionRate(areaName,role,"");
        if(null == areaRoleRate) {
            return "";
        }else {
            //市总体满意率
            List<TotalSampleVo> result = reportDataMapper.queryAreaSatisfactionByXdAndRole("", role);
            String satisfiedRate = getSatisfiedRate2(result);

            double cityRoleRate = Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1));

            if (areaName.equals("市属") || areaName.equals("贵安新区") || role.equals("园长") || role.equals("人大代表/政协委员")) {
                return areaName + role + "综合满意率" + areaRoleRate + "%，" + compareCity(areaRoleRate, cityRoleRate);
            } else {
                double lastRate = reportDataCountyMapper.queryHistoryData(areaName, "-1", role, String.valueOf(CURRENT_YEAR - 1)).get(0);
                return areaName + role + "综合满意率" + areaRoleRate + "%," + compareCity(areaRoleRate, cityRoleRate) + "。" + compareLastYear(areaRoleRate, lastRate);
            }
        }
    }

    @Override
    public Map<String, List<Double>> queryRoleTotalSatisfactionHistoryByAreaAndRole(String areaName, String role) {
        Map<String, List<Double>> dataMap = new HashMap();
        List<TotalSampleVo> result = reportDataMapper.queryAreaSatisfactionByXdAndRole("", role);
        String satisfiedRate = getSatisfiedRate2(result);
        double cityRoleRate = Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1));
        if(areaName.equals("市属") || areaName.equals("贵安新区") || role.equals("园长") || role.equals("人大代表/政协委员")) {
            Double areaCurrentYear =  reportDataCountyMapper.queryTotalSatisfactionRate(areaName,role,"");
            List<Double> area = new ArrayList<>();
            area.add(null == areaCurrentYear? 0.0:areaCurrentYear);
            area.add(cityRoleRate);
            dataMap.put(String.valueOf(CURRENT_YEAR), area);
        }else {

            List<Double> arrayYearBeforeLast = reportDataCountyMapper.queryHistoryData(areaName,"-1",role,String.valueOf(CURRENT_YEAR - 2));
            List<Double> arrayLastYear = reportDataCountyMapper.queryHistoryData(areaName,"-1",role,String.valueOf(CURRENT_YEAR - 1));
            Double arrayCurrentYear =  reportDataCountyMapper.queryTotalSatisfactionRate(areaName,role,"");;

            List<Double> cityYearBeforeLast = reportDataCountyMapper.queryHistoryData("均值","-1",role,String.valueOf(CURRENT_YEAR - 2));
            List<Double> cityLastYear = reportDataCountyMapper.queryHistoryData("均值","-1",role,String.valueOf(CURRENT_YEAR - 1));



            List<Double> area = new ArrayList<>();
            area.addAll(arrayYearBeforeLast);
            area.addAll(arrayLastYear);
            area.add(null == arrayCurrentYear? 0.0:arrayCurrentYear);
            List<Double> city = new ArrayList<>();
            city.addAll(cityYearBeforeLast);
            city.addAll(cityLastYear);
            city.add(cityRoleRate);

            dataMap.put(areaName, area);
            dataMap.put("贵阳市", city);
        }

        return dataMap;
    }

    @Override
    public String queryTotalSatisfactionByAreaAndXd(String areaName, String xd) {
        //区县总体满意率（无%）
        Double areaXdRate =  reportDataCountyMapper.queryTotalSatisfactionRate(areaName,"",xd);
        //市总体满意率
        List<TotalSampleVo> result = reportDataMapper.queryAreaSatisfactionByXdAndRole(xd, "");
        String satisfiedRate = getSatisfiedRate2(result);
        double cityXdRate = Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1));
        if(areaName.equals("市属") || areaName.equals("贵安新区")) {
            return areaName + xd + "综合满意率为" + areaXdRate + "%," + compareCity(areaXdRate, cityXdRate) + "。";
        }else {
            double lastRate = reportDataCountyMapper.queryHistoryData(areaName, xd, "-1", String.valueOf(CURRENT_YEAR - 1)).get(0);
            return areaName + xd + "综合满意率为" + areaXdRate + "%," + compareCity(areaXdRate, cityXdRate) + "。" + compareLastYear(areaXdRate, lastRate);

        }
    }

    @Override
    public Map<String, List<Double>> queryTotalSatisfactionRateByAreaAndXd(String areaName, String xd) {
        Map<String, List<Double>> dataMap = new HashMap();

        List<TotalSampleVo> result = reportDataMapper.queryAreaSatisfactionByXdAndRole(xd, "");
        String satisfiedRate = getSatisfiedRate2(result);
        double cityRoleRate = Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1));

        Double areaCurrentYear =  reportDataCountyMapper.queryTotalSatisfactionRate(areaName,"",xd);
        List<Double> area = new ArrayList<>();

        if(areaName.equals("市属") || areaName.equals("贵安新区") ) {
            area.add(null == areaCurrentYear? 0.0:areaCurrentYear);
            area.add(cityRoleRate);
            dataMap.put(String.valueOf(CURRENT_YEAR), area);
        }else {
            List<Double> areaHistoryList = reportDataCountyMapper.queryHistoryData(areaName,xd,"-1","");
            List<Double> cityHistoryList = reportDataCountyMapper.queryHistoryData("均值",xd,"-1","");
            areaHistoryList.add(null == areaCurrentYear? 0.0:areaCurrentYear);
            cityHistoryList.add(cityRoleRate);
            dataMap.put(areaName, areaHistoryList);
            dataMap.put("贵阳市", cityHistoryList);
        }
        return dataMap;
    }

    @Override
    public String queryAreaTotalSatisfactionByXdAndRole(String areaName, String xd, String role) {
        //区县总体满意率（无%）
        Double areaRoleRate = 0.0;
        List<ProjectIndicatorsVo> projectIndicatorsVos = reportDataMapper.queryProjectIndicatorsByXdAndRole(xd, role);
        List<TotalSampleVo> result = new ArrayList<>();
        LinkedHashSet<String> areaList = projectIndicatorsVos.stream().map(ProjectIndicatorsVo::getAreaName).collect(Collectors.toCollection( LinkedHashSet::new ));
        for(String name : areaList) {
            String score = "";
            double total = 0.0;
            int length = 0;
            for(ProjectIndicatorsVo projectIndicatorsVo : projectIndicatorsVos) {
                if(name.equals(projectIndicatorsVo.getAreaName())) {
                    length += 1;
                    total += projectIndicatorsVo.getScore();
                }
            }
            score = String.format("%.8f", total/length );
            TotalSampleVo vo = new TotalSampleVo(name,score);
            result.add(vo);
        }
        for(TotalSampleVo vo : result) {
            if(areaName.equals(vo.getName())) {
                areaRoleRate = Double.parseDouble(String.format("%.2f", Double.parseDouble(vo.getValue().toString())/5 *100));
            }
        }

        //市综合满意率
        String satisfiedRate = getSatisfiedRate3(result);



        if(null == areaRoleRate) {
            return "";
        }else {
            //市总体满意率
            double cityRoleRate = Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1));

            if (areaName.equals("市属") || areaName.equals("贵安新区") || role.equals("园长") || role.equals("人大代表/政协委员")) {
                return areaName + role  + xd + "综合满意率为" + areaRoleRate + "%，" + compareCity(areaRoleRate, cityRoleRate);
            } else {
                double lastRate = reportDataCountyMapper.queryHistoryData(areaName, xd, role, String.valueOf(CURRENT_YEAR - 1)).get(0);
                return areaName + role + xd + "综合满意率" + areaRoleRate + "%," + compareCity(areaRoleRate, cityRoleRate) + "。" + compareLastYear(areaRoleRate, lastRate);
            }
        }
    }

    @Override
    public Map<String, List<Double>> queryAreaTotalSatisfactionRateByXdAndRole(String areaName, String xd, String role) {
        Map<String, List<Double>> dataMap = new HashMap();


        //区县总体满意率（无%）
        Double areaRoleRate = 0.0;
        List<ProjectIndicatorsVo> projectIndicatorsVos = reportDataMapper.queryProjectIndicatorsByXdAndRole(xd, role);
        List<TotalSampleVo> result = new ArrayList<>();
        LinkedHashSet<String> areaList = projectIndicatorsVos.stream().map(ProjectIndicatorsVo::getAreaName).collect(Collectors.toCollection( LinkedHashSet::new ));
        for(String name : areaList) {
            String score = "";
            double total = 0.0;
            int length = 0;
            for(ProjectIndicatorsVo projectIndicatorsVo : projectIndicatorsVos) {
                if(name.equals(projectIndicatorsVo.getAreaName())) {
                    length += 1;
                    total += projectIndicatorsVo.getScore();
                }
            }
            score = String.format("%.8f", total/length );
            TotalSampleVo vo = new TotalSampleVo(name,score);
            result.add(vo);
        }
        for(TotalSampleVo vo : result) {
            if(areaName.equals(vo.getName())) {
                areaRoleRate = Double.parseDouble(String.format("%.2f", Double.parseDouble(vo.getValue().toString())/5 *100));
            }
        }
        //市综合满意率
        String satisfiedRate = getSatisfiedRate3(result);
        double cityRoleRate = Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1));


        List<Double> area = new ArrayList<>();

        if(areaName.equals("市属") || areaName.equals("贵安新区") || role.equals("园长") || role.equals("人大代表/政协委员")) {
            area.add(null == areaRoleRate? 0.0:areaRoleRate);
            area.add(cityRoleRate);
            dataMap.put(String.valueOf(CURRENT_YEAR), area);
        }else {
            List<Double> areaHistoryList = reportDataCountyMapper.queryHistoryData(areaName,xd,role,"");
            List<Double> cityHistoryList = reportDataCountyMapper.queryHistoryData("均值",xd,role,"");
            areaHistoryList.add(areaRoleRate);
            cityHistoryList.add(cityRoleRate);
            dataMap.put(areaName, areaHistoryList);
            dataMap.put("贵阳市", cityHistoryList);
        }
        return dataMap;
    }

    @Override
    public String queryProjectIndicatorsByXdAndRole(String areaName,String xd, String role) {
        //查询区县学段角色对应的项目指标分
        List<TotalSampleVo> areaProject = reportDataCountyMapper.queryProjectIndicatorsByAreaXdAndRole(areaName, xd, role);
        // 查询全市学段角色对应的项目指标分
        List<TotalSampleVo> cityProject = reportDataCountyMapper.queryProjectIndicatorsByAreaXdAndRole("", xd, role);
        return getProjectIndicatorsString(areaProject,areaName,xd,role) + compareCityProject(areaProject,cityProject);

    }


    @Override
    public Map<String, Object> queryIndexSatisfactionByXdAndRole(String areaName,String xd, String role) {
        Map<String, Object> dataMap = new LinkedHashMap<>();
        List<String> indexNameList = reportDataCountyMapper.queryAreaIndexNameByXdAndRole(areaName,xd,role);
        List<Object> area = new ArrayList<>();
        List<Object> city = new ArrayList<>();
        //查询区县学段角色对应的项目指标分
        List<TotalSampleVo> areaProject = reportDataCountyMapper.queryProjectIndicatorsByAreaXdAndRole(areaName, xd, role);
        if(CollectionUtils.isNotEmpty(areaProject)) {
            for(TotalSampleVo temp:areaProject) {
                area.add(temp.getValue());
            }
        }
        // 查询全市学段角色对应的项目指标分
        List<TotalSampleVo> cityProject = reportDataCountyMapper.queryProjectIndicatorsByAreaXdAndRole("", xd, role);
        if(CollectionUtils.isNotEmpty(cityProject)) {
            for(TotalSampleVo temp:cityProject) {
                city.add(temp.getValue());
            }
        }
        dataMap.put("indexName",indexNameList);
        dataMap.put(areaName,area);
        dataMap.put("贵阳市",city);

        return dataMap;
    }

    private String getProjectIndicatorsString (List<TotalSampleVo> data,String areaName,String xd,String role) {
        if(CollectionUtils.isEmpty(data)) {
            return "";
        }
        List<TotalSampleVo> temp = new ArrayList<>();
        temp.addAll(data);
        Collections.sort(temp);
        StringBuilder result = new StringBuilder();
        result.append(areaName).append(xd).append(role).append("问卷").append(data.size()).append("个调查项目上的满意度水平从高到低分别为：");
        for (TotalSampleVo vo : temp) {
            result.append(vo.getName()).append(vo.getValue()).append("、");
        }
        return result.substring(0,result.length()-1) + "。";
    }

    private List<TotalSampleVo> getAvgProjectIndicators(List<String> indexNameList,List<ProjectIndicatorsVo> ojectIndicatorsList) {
        if(CollectionUtils.isEmpty(indexNameList)){
            return new ArrayList<>();
        }else {
            List<TotalSampleVo> result = new ArrayList<>();
            for (String indexName : indexNameList) {
                double total = 0.00;
                int count = 0;
                for (ProjectIndicatorsVo projectIndicatorsVo : ojectIndicatorsList) {
                    if (indexName.equals(projectIndicatorsVo.getIndexName())) {
                        total += projectIndicatorsVo.getScore();
                        count++;
                    }
                }
                if (total == 0) {
                    result.add(new TotalSampleVo(indexName, 0.00));
                }
                result.add(new TotalSampleVo(indexName, String.format("%.2f", total / count)));
            }
            return result;
        }
    }

    private String getXdRateString (List<TotalSampleVo> data) {
        List<TotalSampleVo> temp = new ArrayList<>();
        temp.addAll(data);
        Collections.sort(temp);
        StringBuilder result = new StringBuilder();
        for (int i = 0;i<temp.size();i++) {
            result.append(temp.get(i).getName()).append(getPercent(Double.parseDouble(temp.get(i).getValue().toString()),5)).append("、");
        }
        return result.substring(0,result.length()-1)+ "。";
    }

    private  String getPercent(double a , double b) {
        if(a == 0 || b == 0) {
            return "0%";
        }
        return String.format("%.2f", a /  b * 100) + "%";
    }

    private  String getSatisfiedRate(List<TotalSampleVo> data) {
        if(CollectionUtils.isEmpty(data)) {
            return "0%";
        }
        Iterator<TotalSampleVo> iterator = data.iterator();
        while(iterator.hasNext()) {
            TotalSampleVo vo = iterator.next();
            if(Double.valueOf(vo.getValue().toString()) == 0){
                iterator.remove();
            }
        }
        double totalRate = 0.0;
        for (TotalSampleVo totalSample : data) {
            totalRate = add(totalRate, Double.parseDouble(totalSample.getValue().toString()));
        }
        totalRate = div(totalRate,data.size(),3);
        return String.format("%.2f", getPercentNo(totalRate,5)) + "%";
    }

    private  String getSatisfiedRate2(List<TotalSampleVo> data) {
        if(CollectionUtils.isEmpty(data)) {
            return "0%";
        }
        Iterator<TotalSampleVo> iterator = data.iterator();
        while(iterator.hasNext()) {
            TotalSampleVo vo = iterator.next();
            if(Double.valueOf(vo.getValue().toString()) == 0){
                iterator.remove();
            }
        }
        double totalRate = 0.0;
        for (TotalSampleVo totalSample : data) {
            totalRate = add(totalRate, Double.parseDouble(totalSample.getValue().toString()));
        }
        totalRate = div(totalRate,data.size(),4);
        return String.format("%.2f", getPercentNo(totalRate,5)) + "%";
    }

    private  String getSatisfiedRate3(List<TotalSampleVo> data) {
        if(CollectionUtils.isEmpty(data)) {
            return "0%";
        }
        Iterator<TotalSampleVo> iterator = data.iterator();
        while(iterator.hasNext()) {
            TotalSampleVo vo = iterator.next();
            if(Double.valueOf(vo.getValue().toString()) == 0){
                iterator.remove();
            }
        }
        double totalRate = 0.0;
        for (TotalSampleVo totalSample : data) {
            totalRate = add(totalRate, Double.parseDouble(totalSample.getValue().toString()));
        }
        totalRate = div(totalRate,data.size(),8);
        return String.format("%.2f", getPercentNo(totalRate,5)) + "%";
    }

    public double add(double v1, double v2) {

        BigDecimal b1 = new BigDecimal(Double.toString(v1));

        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();

    }

    public double div(double v1, double v2, int scale) {

        if (scale < 0) {

            throw new IllegalArgumentException("The scale must be a positive integer or zero");

        }

        BigDecimal b1 = new BigDecimal(Double.toString(v1));

        BigDecimal b2 = new BigDecimal(Double.toString(v2));

        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();

    }

    private  Double getPercentNo(double a , double b) {
        if(a == 0 || b == 0) {
            return 0.0;
        }
        return Double.parseDouble(String.format("%.2f", a /  b * 100));
    }

    private  String compareLastYear(double totalRate,double lastTotalRate) {
        if(totalRate > lastTotalRate) {
            return "在上年基础上上升了"+String.format("%.2f", totalRate-lastTotalRate)+"个百分点";
        }else if(totalRate < lastTotalRate) {
            return "在上年基础上下降了"+String.format("%.2f", lastTotalRate-totalRate)+"个百分点";
        }else {
            return "与上年持平";
        }
    }

    private  String compareCity(double areaRate,double cityRate) {
        if(areaRate > cityRate) {
            return "与贵阳市均值相比，高于均值"+String.format("%.2f", areaRate-cityRate)+"个百分点";
        }else if(areaRate < cityRate) {
            return "与贵阳市均值相比，低于均值"+String.format("%.2f", cityRate-areaRate)+"个百分点";
        }else {
            return "与贵阳市均值相比，持平";
        }
    }

    private String xdCurrentYearcompareLastYear(double currentYearAverage, double lastYearAverage, List<TotalSampleVo> currentYearData, List<TotalSampleVo> lastYearData) {

        if (CollectionUtils.isEmpty(currentYearData)) {
            return "";
        }


        for (TotalSampleVo totalSampleVo : currentYearData) {
            totalSampleVo.setValue(getPercentNo(Double.parseDouble(totalSampleVo.getValue().toString()), 5));
        }

        List<String> up = new ArrayList<>();
        List<String> down = new ArrayList<>();
        List<String> keep = new ArrayList<>();

        for (TotalSampleVo current : currentYearData) {
            for (TotalSampleVo last : lastYearData) {
                if (current.getName().equals(last.getName())) {
                    double currentValue = Double.parseDouble(current.getValue().toString());
                    double lastValue = Double.parseDouble(last.getValue().toString());
                    if (currentValue > lastValue) {
                        up.add(current.getName() + "阶段上升"+ String.format("%.2f", currentValue - lastValue)+"个百分点");
                    } else if (currentValue < lastValue) {
                        down.add(current.getName() + "阶段下降"+ String.format("%.2f", lastValue - currentValue)+"个百分点");
                    } else {
                        keep.add(current.getName() + "阶段保持不变");
                    }
                    break;
                }
            }
        }

        String result = "";

        if(currentYearAverage != lastYearAverage) {
            if(currentYearAverage > lastYearAverage) {
                result = "与上年相比,整体上升" + String.format("%.2f",currentYearAverage - lastYearAverage) + "个百分点，其中，";
            }else {
                result = "与上年相比,整体下降" + String.format("%.2f",lastYearAverage - currentYearAverage) + "个百分点，其中，";
            }
        }else {
            result = "与上年相比,整体保持不变，";
        }
        if(up.size() != 0) {
            for (String str : up) {
                result += str;
                result += "，";
            }
        }

        if(down.size() != 0) {
            for (String str : down) {
                result += str;
                result += "，";
            }
        }
        if(keep.size() != 0) {
            for (String str : keep) {
                result += str;
                result += "，";
            }
        }
        result = result.substring(0, result.length() - 1) + "。";
        return result;

    }

    private String compareCityProject(List<TotalSampleVo> areaProject, List<TotalSampleVo> cityProject) {
        if(CollectionUtils.isEmpty(areaProject)) {
            return "";
        }else {
            List<String> up = new ArrayList<>();
            List<String> down = new ArrayList<>();
            List<String> keep = new ArrayList<>();

            for (TotalSampleVo area : areaProject) {
                for (TotalSampleVo city : cityProject) {
                    if (area.getName().equals(city.getName())) {
                        double areaValue = Double.parseDouble(area.getValue().toString());
                        double cityValue = Double.parseDouble(city.getValue().toString());
                        if (areaValue > cityValue) {
                            up.add(area.getName());
                        } else if (areaValue < cityValue) {
                            down.add(area.getName());
                        } else {
                            keep.add(area.getName());
                        }
                        break;
                    }
                }
            }

            String result = "";

            if(up.size() != 0 && down.size() == 0 && keep.size() == 0) {
                result = "与贵阳市均值相比，所有项目都不同程度高于均值。";
            }else if(up.size() == 0 && down.size() != 0 && keep.size() == 0){
                result = "与贵阳市均值相比，所有项目都不同程度低于均值。";
            }else {
                result = "与贵阳市均值相比，";
                if(up.size() != 0) {
                    for (String str : up) {
                        result += str;
                        result += "、";
                    }
                    result = result.substring(0, result.length() - 1);
                    result += "高于均值，";
                }

                if(down.size() != 0) {
                    for (String str : down) {
                        result += str;
                        result += "、";
                    }
                    result = result.substring(0, result.length() - 1);
                    result += "低于均值，";
                }
                if(keep.size() != 0) {
                    for (String str : keep) {
                        result += str;
                        result += "、";
                    }
                    result = result.substring(0, result.length() - 1);
                    result += "保持不变，";
                }
                result =  result.substring(0, result.length() - 1) + "。";
            }

            return result;
        }

    }
}
